package com.cf.auth.config;

import com.cf.auth.module.SwordClientDetails;
import com.cf.common.constant.AuthConstant;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.common.exceptions.InvalidClientException;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

/**
 * 自定义客户端信息查询
 * @author ChenFeng
 * @date 2021/11/8 6:08 下午
 * @description
 */
@Component
public class SwordClientDetailsService extends JdbcClientDetailsService {

    public SwordClientDetailsService(DataSource dataSource) {
        super(dataSource);
    }

    @Override
    public ClientDetails loadClientByClientId(String clientId) throws InvalidClientException {
        try {
            ClientDetails clientDetails = super.loadClientByClientId(clientId);
            SwordClientDetails swordClientDetails = new SwordClientDetails();
            swordClientDetails.setClientId(clientDetails.getClientId());
            swordClientDetails.setResourceIds(clientDetails.getResourceIds());
            swordClientDetails.setSecretRequired(clientDetails.isSecretRequired());
            swordClientDetails.setClientSecret(AuthConstant.ENCRYPT_BCRYPT + clientDetails.getClientSecret());
            swordClientDetails.setScoped(clientDetails.isScoped());
            swordClientDetails.setScope(clientDetails.getScope());
            swordClientDetails.setAuthorizedGrantTypes(clientDetails.getAuthorizedGrantTypes());
            swordClientDetails.setRegisteredRedirectUri(clientDetails.getRegisteredRedirectUri());
            swordClientDetails.setAuthorities(clientDetails.getAuthorities());
            swordClientDetails.setAccessTokenValiditySeconds(clientDetails.getAccessTokenValiditySeconds());
            swordClientDetails.setRefreshTokenValiditySeconds(clientDetails.getRefreshTokenValiditySeconds());
            swordClientDetails.setAutoApprove(false);
            swordClientDetails.setAdditionalInformation(clientDetails.getAdditionalInformation());
            return swordClientDetails;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }
}
